package vn.appmobi.comictp;

import vn.gq.tym.scr.CategoryScr;
import vn.gq.tym.scr.IntroScr;
import vn.gq.tym.scr.TabFragment;
import vn.gq.tym.utils.DialogHelper;
import vn.gq.tym.utils.FileUtils;
import vn.gq.tym.utils.GooglePlay;
import vn.gq.tym.utils.IDialogHelper;
import vn.gq.tym.widget.SwipeyTabs;
import vn.gq.tym.widget.SwipeyTabsAdapter;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.startapp.android.publish.StartAppAd;

public class MainActivity extends BaseActivity {

	private StartAppAd startAppAd = new StartAppAd(this);
	
	private static final String [] TITLES = {
		"GIỚI THIỆU",
		"DANH MỤC",
	};
//	private HtmlAd htmlAd = null;
	private SwipeyTabs mTabs;
	private ViewPager mViewPager;
	private ImageLoader imagerLoader = ImageLoader.getInstance();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		StartAppAd.init(this, AppConfig.STARTAPP_DEV_ID, AppConfig.STARTAPP_APP_ID);
		StartAppAd.showSlider(this);
		String subTitle = getString(R.string.author);
		if (!"".equals(subTitle)) {
			getSupportActionBar().setSubtitle(subTitle);
		}
		setContentView(R.layout.activity_main);
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mViewPager.setPageMargin(10);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
				getSupportFragmentManager());
		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setOffscreenPageLimit(2);
		if (FileUtils.isAssetFileExists(this, "description"))
			mViewPager.setCurrentItem(1);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.main, menu);
//		
//		SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
//		searchView.setQueryHint(getString(R.string.search));
//		
//		menu.add("Search")
//		.setIcon(R.drawable.ic_action_search)
//		.setActionView(searchView)
//		.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case R.id.menu_gostore:
				GooglePlay.startActivityForPub(this, "pub:AppMobi");
				break;
			case R.id.menu_rating:
				GooglePlay.startAcitivityForDetail(this);
				break;
			case  R.id.menu_contact:
				sendEmail();
				break;
			case R.id.menu_clearcache:
				imagerLoader.clearMemoryCache();
				imagerLoader.clearDiskCache();
				Toast.makeText(this, getString(R.string.clearcache_notification), Toast.LENGTH_SHORT).show();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
	SwipeyTabsAdapter {

		private final Context mContext;
		
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
		
			this.mContext = context;
		}
		
		@Override
		public Fragment getItem(int position) {
			if (FileUtils.isAssetFileExists(mContext, "description")) {
				switch(position) {
					case 0:
						return IntroScr.newInstance();
					case 1:
						return CategoryScr.newInstance("asset://gzip:data");
					default:
						return TabFragment.newInstance();
				}
			}
			return CategoryScr.newInstance("asset://gzip:data");
		}
		
		@Override
		public int getCount() {
			return TITLES.length;
		}
		
		public TextView getTab(final int position, SwipeyTabs root) {
			TextView view = (TextView) LayoutInflater.from(mContext).inflate(
					R.layout.swipey_tab_indicator, root, false);
			view.setText(TITLES[position]);
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			
			return view;
		}
	}
	
	public void sendEmail() {
		PackageInfo pkgInfo = null;
		try {
			pkgInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		String mEmailBody = String.format("\n\n\n\n\n\n" +
				"-------------------" +
				"\nTên ứng dụng: %s\nMã ứng dụng: %s", getString(R.string.app_name), getPackageName());
		if (pkgInfo != null) {
			mEmailBody += String.format("\nMã phiên bản: %d", pkgInfo.versionCode);
		}
		mEmailBody += "\n-------------------";
		
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.putExtra(Intent.EXTRA_SUBJECT, "Góp ý, nhận xét, yêu cầu truyện");
		intent.putExtra(Intent.EXTRA_TEXT, mEmailBody);
		intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "ungdungviet.llc@gmail.com" });
		intent.setType("message/rfc822");
		try {
			startActivity(Intent.createChooser(intent, "Chọn ứng dụng gửi mail"));
		} catch(ActivityNotFoundException e) {
			Toast.makeText(this, "Không tìm thấy ứng dụng email trong máy", Toast.LENGTH_SHORT).show();
		}
	}

	
	
	@Override
	public void onBackPressed() {
		DialogHelper.showExitDialog(this, "Hãy dành chút thời gian đánh giá cho ứng dụng!", new IDialogHelper() {
			
			@Override
			public void onOk() {
				GooglePlay.startAcitivityForDetail(MainActivity.this);
			}
			
			@Override
			public void onCancel() {
//				onDestroy();
//				System.runFinalizersOnExit(true);
//				System.exit(0);
				startAppAd.showAd();
				finish();
			}
		});
	}

	
	@Override
	protected void onPause() {
		super.onPause();
		startAppAd.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		startAppAd.onResume();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
